package com.xl.basic.utils;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import com.xl.basic.entity.Properties;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 文件上传工具
 *
 * @author 钟勇
 * Create in 2023/8/23 15:58
 */

public class FileUtils {

    /**
     * 上传图片
     *
     * @param file file
     * @return result
     */
    public static Result<String> uploadImage(MultipartFile file) {
        if (file == null) {
            return ResultEnums.ParamError.getResult("未找到文件");
        }


        String contentType = file.getContentType();
        if (StrUtil.isBlank(contentType)) {
            return ResultEnums.ParamError.getResult("未知的文件类型");
        }

        List<String> allowTypeDict = ListUtil.of("jpg", "jpeg", "png", "gif", "bmp");
        if (allowTypeDict.stream().noneMatch(item -> contentType.toLowerCase().contains(item))) {
            return ResultEnums.ParamError.getResult("不支持的图片格式");
        }

        return uploadFile(file);
    }

    /**
     * 上传文件
     *
     * @param file file
     * @return result
     */
    public static Result<String> uploadFile(MultipartFile file) {
        if (file == null) {
            return ResultEnums.ParamError.getResult("未找到文件");
        }
        String suffix = "";

        String oriFileName = file.getOriginalFilename();
        if (StrUtil.isNotBlank(oriFileName)) {
            String[] strArray = oriFileName.split("\\.");
            suffix = strArray[strArray.length - 1].toLowerCase();
        }
        Result<UploadInfo> uploadInfoRes = getUploadInfo(suffix);
        if (uploadInfoRes.isErr()) {
            return uploadInfoRes.create();
        }

        UploadInfo uploadInfo = uploadInfoRes.getResult();

        try {
            file.transferTo(new File(uploadInfo.uploadDir));
        } catch (IOException e) {
            return ResultEnums.BusinessError.getResult("文件存储失败");
        }


        return ResultEnums.Success.getDataResult(uploadInfo.getVisitPath());
    }

    /**
     * 生成本次上传的信息
     *
     * @param suffix 文件后缀
     * @return result
     */
    public static Result<UploadInfo> getUploadInfo(String suffix) {
        //获取配置
        Properties.File fileProp = PropUtils.getProp().getFile();

        String currPath = "/" + LocalDateTimeUtil.format(LocalDateTime.now(), DateTimeFormatter.BASIC_ISO_DATE);
        String fileName = IdUtil.simpleUUID() + (StrUtil.isNotBlank(suffix) ? ("." + suffix) : "");

        String uploadDir = (SystemUtil.getOsInfo().isWindows() ? fileProp.getWindowPath() : fileProp.getLinuxPath()) + currPath;
        String visitPath = fileProp.getVisitPath() + currPath;

        File pathFile = new File(uploadDir);
        if (!pathFile.exists()) {
            if (!pathFile.mkdirs()) {
                return ResultEnums.BusinessError.getResult("上传目录创建失败");
            }
        }

        visitPath += "/" + fileName;
        uploadDir += "/" + fileName;

        UploadInfo info = new UploadInfo().setVisitPath(visitPath).setUploadDir(uploadDir);
        return ResultEnums.Success.getDataResult(info);
    }

    @Data
    @Accessors(chain = true)
    public static class UploadInfo {
        private String visitPath;
        private String uploadDir;
    }
}
